package cn.kailangtu.dataspot;

import android.app.ActivityManager;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import android.os.SystemClock;
import android.telephony.PhoneStateListener;
import android.telephony.SignalStrength;
import android.telephony.TelephonyCallback;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;
import cn.kailangtu.commonevents.eventEntity.AutoLockEvent;
import cn.kailangtu.commonevents.eventEntity.ControlsClickEvent;
import cn.kailangtu.commonevents.eventEntity.ControlsClickSubEvent;
import cn.kailangtu.commonevents.eventEntity.DataBeanChangedEvent;
import cn.kailangtu.commonevents.eventEntity.FragmentChangedEvent;
import cn.kailangtu.commonevents.eventEntity.KeyboardConfirmActionEvent;
import cn.kailangtu.commonevents.eventEntity.KeyboardConfirmCloseEvent;
import cn.kailangtu.commonevents.eventEntity.KeyboardConfirmOpenEvent;
import cn.kailangtu.commonevents.eventEntity.KeyboardLockerActionEvent;
import cn.kailangtu.commonevents.eventEntity.KeyboardLockerCloseEvent;
import cn.kailangtu.commonevents.eventEntity.KeyboardLockerConfirmActionEvent;
import cn.kailangtu.commonevents.eventEntity.KeyboardLockerConfirmResultEvent;
import cn.kailangtu.commonevents.eventEntity.KeyboardLockerOpenEvent;
import cn.kailangtu.commonevents.eventEntity.KeyboardNumberActionEvent;
import cn.kailangtu.commonevents.eventEntity.KeyboardNumberCloseEvent;
import cn.kailangtu.commonevents.eventEntity.KeyboardNumberInputEvent;
import cn.kailangtu.commonevents.eventEntity.KeyboardNumberOpenEvent;
import cn.kailangtu.commonevents.eventEntity.KeyboardSelectionActionEvent;
import cn.kailangtu.commonevents.eventEntity.KeyboardSelectionCloseEvent;
import cn.kailangtu.commonevents.eventEntity.KeyboardSelectionOpenEvent;
import cn.kailangtu.commonevents.eventEntity.KeyboardStopActionEvent;
import cn.kailangtu.commonevents.eventEntity.KeyboardStopCloseEvent;
import cn.kailangtu.commonevents.eventEntity.KeyboardStopOpenEvent;
import cn.kailangtu.commonevents.eventEntity.KeyboardTimeActionEvent;
import cn.kailangtu.commonevents.eventEntity.KeyboardTimeCloseEvent;
import cn.kailangtu.commonevents.eventEntity.KeyboardTimeOpenEvent;
import cn.kailangtu.commonevents.eventEntity.OnFragmentChangeEvent;
import cn.kailangtu.commonevents.eventEntity.OpenContactEvent;
import cn.kailangtu.commonevents.eventEntity.OpenPrincipleEvent;
import cn.kailangtu.commonevents.eventEntity.RealViewCloseEvent;
import cn.kailangtu.commonevents.eventEntity.RealViewOpenEvent;
import cn.kailangtu.commonevents.eventEntity.TemperatureDataEvent;
import cn.kailangtu.commonevents.eventEntity.TimeoutEvent;
import cn.kailangtu.commonevents.eventEntity.TotalPopDataChangedEvent;
import cn.kailangtu.commontools.APPSPUtils;
import cn.kailangtu.commontools.AppUtils;
import cn.kailangtu.commontools.AppVariable;
import cn.kailangtu.commontools.CommonUtils;
import cn.kailangtu.commontools.ConnectUtils;
import cn.kailangtu.commontools.EthernetUtils;
import cn.kailangtu.commontools.KeyboardUtils;
import cn.kailangtu.commontools.MyCalendar;
import cn.kailangtu.dataspot.broadcast.UsbDeviceReceiver;
import cn.kailangtu.dataspot.camera.AvcPlayerHelper;
import cn.kailangtu.dataspot.data.HighData;
import cn.kailangtu.dataspot.data.PageIndex;
import cn.kailangtu.dataspot.data.consts.ControlEventValues;
import cn.kailangtu.dataspot.data.consts.ControlIndex;
import cn.kailangtu.dataspot.data.consts.ControlType;
import cn.kailangtu.dataspot.data.consts.MainButtonValues;
import cn.kailangtu.dataspot.data.context.KeyboardConfirmContext;
import cn.kailangtu.dataspot.data.context.KeyboardContext;
import cn.kailangtu.dataspot.data.context.KeyboardSelectContext;
import cn.kailangtu.dataspot.data.context.MainContext;
import cn.kailangtu.dataspot.data.context.RealViewContext;
import cn.kailangtu.dataspot.data.context.SelectContext;
import cn.kailangtu.dataspot.data.status.ConnectStatus;
import cn.kailangtu.dataspot.databinding.ActivityMainBinding;
import cn.kailangtu.dataspot.db.NewTotalDataEntity;
import cn.kailangtu.dataspot.tasks.BaseTask;
import cn.kailangtu.dataspot.total.RealViewTotalData;
import cn.kailangtu.dataspot.total.TotalData;
import cn.kailangtu.dataspot.widget.AvcPlayer;
import cn.kailangtu.serialutils.api.SerialPortApi;
import cn.kailangtu.serialutils.modbus.modbusUtil;
import android.view.Menu;
import android.view.MenuItem;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.TextView;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.text.DecimalFormat;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    private AppBarConfiguration appBarConfiguration;
    private ActivityMainBinding binding;
    private int controlIndex = ControlIndex.EMPTY; //0,1,2,3,4(实时数据，参数设置，故障记录，厂家设置，开关实验)
    private int controlType = ControlType.MAIN; //0,是主菜音，1是子菜单
    private int curreFragment;
    private RealViewTotalData realViewTotalData;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        closeVirtualKeys();
        EthernetUtils.resetIp();
        moveToFront();
        DataSpotApplication.isOpen = true;
        Log.d("SHOOTLEE", String.valueOf(System.currentTimeMillis()));

        binding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());


        NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_content_main);

        initListen();
        List<NetworkInfo> ls = ConnectUtils.getNetworkInfo(this);
        for (NetworkInfo info : ls) {
            Log.e("SHOOTLEE", info.getTypeName());
        }


//        if(AppVariable.platform_version == 450){
//            SerialPortApi485.getInstance().openSerialPort("/dev/ttyHSL0",256000,0);
//        }
//        else {
//            SerialPortApi.getInstance().openSerialPortV2("", 256000, 0);
//        }
        initIPCameraView1();
        // testSpeed();
        resetPlatform();


        APPSPUtils.getInstance().putSplashTitle("智能移变高压侧");
        //registerAll();
        //registerBluetooth();

        resetElement();
        // testResetOpenCamera();

        //testTotalData();
        // testAddData();

        binding.tvVersionCode.setText("版本号:"+BuildConfig.VERSION_CODE);
    }

    @Override
    public void onResume() {
        //隐藏虚拟按键，并且全屏
        super.onResume();
        if (Build.VERSION.SDK_INT > 11 && Build.VERSION.SDK_INT < 19) { // lower api
            View v = this.getWindow().getDecorView();
            v.setSystemUiVisibility(View.GONE);
        } else if (Build.VERSION.SDK_INT >= 19) {
            //for new api versions.
            View decorView = getWindow().getDecorView();
            int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY | View.SYSTEM_UI_FLAG_FULLSCREEN;
            decorView.setSystemUiVisibility(uiOptions);
        }

        getWindow().setStatusBarColor(Color.TRANSPARENT);// Color.TRANSPARENT = 0 表示#00000000即透明颜色
        getWindow().setNavigationBarColor(Color.TRANSPARENT);

        //隐藏状态栏
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);


    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public boolean onSupportNavigateUp() {
        NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_content_main);
        return NavigationUI.navigateUp(navController, appBarConfiguration)
                || super.onSupportNavigateUp();
    }

    @Override
    public void onStart() {
        super.onStart();
        Log.d("SHOOTLEE", "onStart");
        EventBus.getDefault().register(this);

        realViewTotalData = new RealViewTotalData(binding.lineChartRealViewDianYa, binding.lineChartRealViewDianLiu);


        if (APPSPUtils.getInstance().isStop()) {
            EventBus.getDefault().post(new OnFragmentChangeEvent(R.layout.fragment_switch_test));
            EventBus.getDefault().post(new AutoLockEvent());
            EventBus.getDefault().post(new KeyboardStopOpenEvent());

        }
    }

    @Override
    public void onStop() {
        super.onStop();
        Log.d("SHOOTLEE", "onStop");
        EventBus.getDefault().unregister(this);
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(FragmentChangedEvent event) {
        // Do something

        Log.d("SHOOTLEE", String.valueOf(event.getFragmentId()));
        status.currentFragment = event.getFragmentId();
        status.resetLastOptionTime();
        MainContext.reset();
        if (event.getFragmentId() == R.layout.fragment_real_picture) {
            if (binding.rlRealViewContainer.getVisibility() == View.VISIBLE) {
                binding.btnRealViewClose.setVisibility(View.VISIBLE);
            } else {
                binding.btnRealViewClose.setVisibility(View.GONE);
            }
            //openRealView();
            resetKeyboard();


            binding.btnCommonSettingNormal.setVisibility(View.VISIBLE);
            binding.btnCommonSettingSelection.setVisibility(View.GONE);

            binding.btnLogNormal.setVisibility(View.VISIBLE);
            binding.btnLogSelection.setVisibility(View.GONE);

            binding.btnFactorySettingNormal.setVisibility(View.VISIBLE);
            binding.btnFactorySettingSelection.setVisibility(View.GONE);

            binding.btnSwitchTestNormal.setVisibility(View.VISIBLE);
            binding.btnSwitchTestSelection.setVisibility(View.GONE);

            binding.tvTitle.setText("智能移变高压侧");
            //binding.rlMainDefault.setVisibility(View.VISIBLE);
            binding.getRoot().setBackgroundResource(R.drawable.bg_main);


        } else if (event.getFragmentId() == R.layout.fragment_common_setting) {

            binding.btnRealViewClose.setVisibility(View.VISIBLE);
            binding.btnRealPicNormal.setVisibility(View.VISIBLE);
            binding.btnRealPicSelection.setVisibility(View.GONE);

            binding.btnCommonSettingNormal.setVisibility(View.GONE);
            binding.btnCommonSettingSelection.setVisibility(View.VISIBLE);

            binding.btnLogNormal.setVisibility(View.VISIBLE);
            binding.btnLogSelection.setVisibility(View.GONE);

            binding.btnFactorySettingNormal.setVisibility(View.VISIBLE);
            binding.btnFactorySettingSelection.setVisibility(View.GONE);

            binding.btnSwitchTestNormal.setVisibility(View.VISIBLE);
            binding.btnSwitchTestSelection.setVisibility(View.GONE);

            binding.tvTitle.setText("智能移变高压侧");
            //binding.rlMainDefault.setVisibility(View.GONE);
            binding.getRoot().setBackgroundResource(R.drawable.bg_main_ex);
        } else if (event.getFragmentId() == R.layout.fragment_exception_log) {

            binding.btnRealViewClose.setVisibility(View.VISIBLE);
            binding.btnRealPicNormal.setVisibility(View.VISIBLE);
            binding.btnRealPicSelection.setVisibility(View.GONE);

            binding.btnCommonSettingNormal.setVisibility(View.VISIBLE);
            binding.btnCommonSettingSelection.setVisibility(View.GONE);

            binding.btnLogNormal.setVisibility(View.GONE);
            binding.btnLogSelection.setVisibility(View.VISIBLE);

            binding.btnFactorySettingNormal.setVisibility(View.VISIBLE);
            binding.btnFactorySettingSelection.setVisibility(View.GONE);

            binding.btnSwitchTestNormal.setVisibility(View.VISIBLE);
            binding.btnSwitchTestSelection.setVisibility(View.GONE);

            binding.tvTitle.setText("智能移变高压侧");
            //binding.rlMainDefault.setVisibility(View.GONE);
            binding.getRoot().setBackgroundResource(R.drawable.bg_main_ex);
        } else if (event.getFragmentId() == R.layout.fragment_factory_setting) {

            binding.btnRealViewClose.setVisibility(View.VISIBLE);
            binding.btnRealPicNormal.setVisibility(View.VISIBLE);
            binding.btnRealPicSelection.setVisibility(View.GONE);

            binding.btnCommonSettingNormal.setVisibility(View.VISIBLE);
            binding.btnCommonSettingSelection.setVisibility(View.GONE);

            binding.btnLogNormal.setVisibility(View.VISIBLE);
            binding.btnLogSelection.setVisibility(View.GONE);

            binding.btnFactorySettingNormal.setVisibility(View.GONE);
            binding.btnFactorySettingSelection.setVisibility(View.VISIBLE);

            binding.btnSwitchTestNormal.setVisibility(View.VISIBLE);
            binding.btnSwitchTestSelection.setVisibility(View.GONE);

            binding.tvTitle.setText("智能移变高压侧");
            //binding.rlMainDefault.setVisibility(View.GONE);
            binding.getRoot().setBackgroundResource(R.drawable.bg_main_ex);
        } else if (event.getFragmentId() == R.layout.fragment_switch_test) {

            binding.btnRealViewClose.setVisibility(View.VISIBLE);
            binding.btnRealPicNormal.setVisibility(View.VISIBLE);
            binding.btnRealPicSelection.setVisibility(View.GONE);

            binding.btnCommonSettingNormal.setVisibility(View.VISIBLE);
            binding.btnCommonSettingSelection.setVisibility(View.GONE);

            binding.btnLogNormal.setVisibility(View.VISIBLE);
            binding.btnLogSelection.setVisibility(View.GONE);

            binding.btnFactorySettingNormal.setVisibility(View.VISIBLE);
            binding.btnFactorySettingSelection.setVisibility(View.GONE);

            binding.btnSwitchTestNormal.setVisibility(View.GONE);
            binding.btnSwitchTestSelection.setVisibility(View.VISIBLE);

            binding.tvTitle.setText("智能移变高压侧");
            //binding.rlMainDefault.setVisibility(View.GONE);
            binding.getRoot().setBackgroundResource(R.drawable.bg_main_ex);
        }
        binding.rlLogChildButtonContainer.setVisibility(View.GONE);
        controlType = ControlType.SUB;
    }

    int titleClickCount = 0;
    long titleLastClickTime = 0;
    boolean canClick = true;

    private void initListen() {
        binding.tvTitle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                /*
                if(canClick) {
                    if ((System.currentTimeMillis() - titleLastClickTime) < 1000) {
                        titleLastClickTime = System.currentTimeMillis();
                        titleClickCount++;
                        if (titleClickCount >= 10) {
                            canClick = false;
                            Intent intent = new Intent(MainActivity.this, MainLowActivity.class);
                            startActivity(intent);
                            MainActivity.this.finish();
                        }
                    } else {
                        titleLastClickTime = System.currentTimeMillis();
                        titleClickCount = 0;
                    }
                }

                 */
            }
        });


        binding.btnRealPicNormal.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (canToOther()) {
                    //EventBus.getDefault().post(new OnFragmentChangeEvent(R.layout.fragment_real_picture));
                    openRealView();

                }
            }
        });

        binding.btnLogNormal.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (canToOther()) {

                    binding.rlLogChildButtonContainer.setVisibility(View.VISIBLE);
                    //EventBus.getDefault().post(new OnFragmentChangeEvent(R.layout.fragment_exception_log));

                }
            }
        });

        binding.btnLogSelection.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (canToOther()) {

                    binding.rlLogChildButtonContainer.setVisibility(View.VISIBLE);
                    //EventBus.getDefault().post(new OnFragmentChangeEvent(R.layout.fragment_exception_log));
                }
            }
        });

        binding.btnLogChildErrNormal.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                status.logViewIndex = 1;
                EventBus.getDefault().post(new OnFragmentChangeEvent(R.layout.fragment_exception_log));
                binding.rlLogChildButtonContainer.setVisibility(View.GONE);
            }
        });

        binding.btnLogChildErrSelection.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                status.logViewIndex = 1;
                EventBus.getDefault().post(new OnFragmentChangeEvent(R.layout.fragment_exception_log));
                binding.rlLogChildButtonContainer.setVisibility(View.GONE);
            }
        });

        binding.btnLogChildLuboNormal.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                status.logViewIndex = 2;
                EventBus.getDefault().post(new OnFragmentChangeEvent(R.layout.fragment_exception_log));
                binding.rlLogChildButtonContainer.setVisibility(View.GONE);
            }
        });

        binding.btnLogChildLuboSelection.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                status.logViewIndex = 2;
                EventBus.getDefault().post(new OnFragmentChangeEvent(R.layout.fragment_exception_log));
                binding.rlLogChildButtonContainer.setVisibility(View.GONE);
            }
        });

        binding.btnLogChildOptionNormal.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                status.logViewIndex = 3;
                EventBus.getDefault().post(new OnFragmentChangeEvent(R.layout.fragment_exception_log));
                binding.rlLogChildButtonContainer.setVisibility(View.GONE);
            }
        });
        binding.btnLogChildOptionSelection.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                status.logViewIndex = 3;
                EventBus.getDefault().post(new OnFragmentChangeEvent(R.layout.fragment_exception_log));
                binding.rlLogChildButtonContainer.setVisibility(View.GONE);
            }
        });

        binding.btnFactorySettingNormal.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (canToOther()) {
                    status.currentPwdTargetSourceId = R.layout.fragment_factory_setting;
                    binding.rlKeyboardLockerConfirm.setVisibility(View.VISIBLE);
                    //EventBus.getDefault().post(new OnFragmentChangeEvent(R.layout.fragment_factory_setting));
                }
            }
        });

        binding.btnSwitchTestNormal.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (canToOther()) {
                    EventBus.getDefault().post(new OnFragmentChangeEvent(R.layout.fragment_switch_test));
                }
            }
        });

        binding.btnCommonSettingNormal.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (canToOther()) {
                    status.currentPwdTargetSourceId = R.layout.fragment_common_setting;
                    binding.rlKeyboardLockerConfirm.setVisibility(View.VISIBLE);
                    //EventBus.getDefault().post(new OnFragmentChangeEvent(R.layout.fragment_common_setting));
                }
            }
        });

        binding.btnControlEntry.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (canToOther()) {
                    EventBus.getDefault().post(new ControlsClickEvent(1));
                }
            }
        });

        binding.btnControlLeft.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                EventBus.getDefault().post(new ControlsClickEvent(2));
                KeyboardUtils.sendKeyboardEvent(KeyEvent.KEYCODE_DPAD_DOWN);
            }
        });

        binding.btnControlRight.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                EventBus.getDefault().post(new ControlsClickEvent(3));
                KeyboardUtils.sendKeyboardEvent(KeyEvent.KEYCODE_DPAD_UP);
            }
        });

        binding.btnRealViewClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!status.isStop) {
                    if (status.currentFragment == R.layout.fragment_real_picture || status.currentFragment == R.layout.fragment_real_picture_low) {
                        closeRealView();
                    } else {
                        closeRealView();
                        EventBus.getDefault().post(new OnFragmentChangeEvent(R.layout.fragment_real_picture));
                    }
                }
            }
        });


        binding.btnRealViewNextPage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (binding.rlRealViewContainerItem2.getVisibility() == View.VISIBLE) {

                    binding.rlRealViewContainerItem1.setVisibility(View.VISIBLE);
                    binding.rlRealViewContainerItem2.setVisibility(View.GONE);
                } else {
                    binding.rlRealViewContainerItem1.setVisibility(View.GONE);
                    binding.rlRealViewContainerItem2.setVisibility(View.VISIBLE);
                }
            }
        });

        binding.tvPageDayLeft.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                currentMyCalendar.addDays(-1);
                resetPageCondition(currentMyCalendar);
            }
        });
        binding.tvPageDayRight.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                currentMyCalendar.addDays(1);
                resetPageCondition(currentMyCalendar);
            }
        });
        binding.tvPageHourLeft.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                currentMyCalendar.addHours(-1);
                resetPageCondition(currentMyCalendar);
            }
        });
        binding.tvPageHourRight.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                currentMyCalendar.addHours(1);
                resetPageCondition(currentMyCalendar);
            }
        });
        binding.tvPageMinuteLeft.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                currentMyCalendar.addMinutes(-1);
                resetPageCondition(currentMyCalendar);
            }
        });
        binding.tvPageMinuteRight.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                currentMyCalendar.addMinutes(1);
                resetPageCondition(currentMyCalendar);
            }
        });
        binding.tvPageMonthLeft.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                currentMyCalendar.addMonths(-1);
                resetPageCondition(currentMyCalendar);
            }
        });
        binding.tvPageMonthRight.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                currentMyCalendar.addMonths(1);
                resetPageCondition(currentMyCalendar);
            }
        });
        binding.btnPageFind.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                realViewTotalData.find(currentMyCalendar);

            }
        });

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(TimeoutEvent event) {
        closeRealView();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(OpenContactEvent event)
    {
        binding.rlHelpContact.setVisibility(View.VISIBLE);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(OpenPrincipleEvent event)
    {
        binding.rlHelpPrinciple.setVisibility(View.VISIBLE);
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(KeyboardLockerConfirmResultEvent event) {

        if (event.isSuccess()) {
            EventBus.getDefault().post(new OnFragmentChangeEvent(status.currentPwdTargetSourceId));
            binding.rlKeyboardLockerConfirm.setVisibility(View.GONE);
        } else {
            binding.rlKeyboardLockerConfirm.setVisibility(View.GONE);
        }

        controlType = ControlType.MAIN;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(KeyboardConfirmCloseEvent event) {
        binding.rlKeyboardConfirm.setVisibility(View.GONE);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(KeyboardLockerCloseEvent event) {
        binding.rlKeyboardLocker.setVisibility(View.GONE);
    }

    int lastValue = Integer.MIN_VALUE;
    boolean isReset = false;

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(DataBeanChangedEvent event) {

        int data3527 = HighData.getInstance().getValue(3527);
        if (data3527 == 2) {
            if (!isReset) {
                isReset = true;
                APPSPUtils.getInstance().putLastMainPage(2);
                this.startActivity(new Intent(this, MainLowActivity.class));
                this.finish();
            }

            return;
        }


        status.plcPageIndex = HighData.getInstance().getValue(3529);
        if (lastValue != status.plcPageIndex) {
            lastValue = status.plcPageIndex;
            Log.d("TAGECHANGE", "LAST:" + lastValue);
        }
        if (status.localToPlc == 1) {
            if (status.plcPageIndex == status.localPageIndex) {
                status.localToPlc = 0;
            }
        } else if (status.localToPlc == 2) {
            if (status.plcPageIndex == status.localPageIndex) {
                status.localToPlc = 0;
            }
        } else {
            if (status.plcPageIndex != status.localPageIndex) {
                if (status.isStop) {
                    BaseTask.toNewPage(status.localPageIndex);
                } else {
                    status.localToPlc = 2;
                    switch (status.plcPageIndex) {
                        case PageIndex.H_MAIN:
                        case PageIndex.L_MAIN:
                            binding.btnRealViewClose.callOnClick();
                            break;
                        case PageIndex.H_REAL_VIEW:
                            EventBus.getDefault().post(new OnFragmentChangeEvent(R.layout.fragment_real_picture));
                            break;
                        case PageIndex.H_LOG:
                            EventBus.getDefault().post(new OnFragmentChangeEvent(R.layout.fragment_exception_log));
                            break;
                        case PageIndex.H_FACTORY_SET:
                            EventBus.getDefault().post(new OnFragmentChangeEvent(R.layout.fragment_factory_setting));
                            break;
                        case PageIndex.H_SWITCH:
                        case PageIndex.H_STOP:
                            EventBus.getDefault().post(new OnFragmentChangeEvent(R.layout.fragment_switch_test));
                            break;
                        case PageIndex.L_REAL_VIEW:
                            EventBus.getDefault().post(new OnFragmentChangeEvent(R.layout.fragment_real_picture_low));
                            break;
                        case PageIndex.L_LOG:
                            EventBus.getDefault().post(new OnFragmentChangeEvent(R.layout.fragment_exception_log_low));
                            break;
                        case PageIndex.L_FACTORY_SET:
                            EventBus.getDefault().post(new OnFragmentChangeEvent(R.layout.fragment_factory_setting_low));
                            break;
                        case PageIndex.L_SWITCH:
                        case PageIndex.L_STOP:
                            EventBus.getDefault().post(new OnFragmentChangeEvent(R.layout.fragment_switch_test_low));
                            break;
                    }
                }
            }
        }

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(ControlsClickEvent event) {
        Log.d("CONTROL", "onMessageEvent==>Click==>" + event.getClickValue());
        if(binding.rlHelpContact.getVisibility() == View.VISIBLE)
        {
            binding.rlHelpContact.setVisibility(View.GONE);
        }
        else if(binding.rlHelpPrinciple.getVisibility() == View.VISIBLE)
        {
            binding.rlHelpPrinciple.setVisibility(View.GONE);
        }
        else if (binding.rlSelector.getVisibility() == View.VISIBLE) {
            EventBus.getDefault().post(new KeyboardSelectionActionEvent(event.getClickValue(), null));
        } else if (binding.rlKeyboard.getVisibility() == View.VISIBLE) {
            EventBus.getDefault().post(new KeyboardNumberActionEvent(event.getClickValue(), ""));
        } else if (binding.rlKeyboardLockerConfirm.getVisibility() == View.VISIBLE) {
            EventBus.getDefault().post(new KeyboardLockerConfirmActionEvent(event.getClickValue()));
        } else if (binding.rlKeyboardTime.getVisibility() == View.VISIBLE) {
            EventBus.getDefault().post(new KeyboardTimeActionEvent(event.getClickValue()));
        } else if (binding.rlKeyboardLocker.getVisibility() == View.VISIBLE) {
            EventBus.getDefault().post(new KeyboardLockerActionEvent(event.getClickValue()));
        } else if (binding.rlKeyboardConfirm.getVisibility() == View.VISIBLE) {
            EventBus.getDefault().post(new KeyboardConfirmActionEvent(event.getClickValue()));
        } else if (binding.rlKeyboardStop.getVisibility() == View.VISIBLE) {
            EventBus.getDefault().post(new KeyboardStopActionEvent(event.getClickValue()));
        } else if (binding.rlRealViewContainer.getVisibility() == View.VISIBLE) {
            switch (event.getClickValue()) {
                case ControlEventValues.ENTRY:
                    RealViewContext.entry();
                    break;
                case ControlEventValues.LEFT:
                    if (RealViewContext.getSelectedView() == binding.btnRealViewNextPage) {
                        if (binding.rlRealViewContainerItem2.getVisibility() == View.VISIBLE) {
                            RealViewContext.setSelectedView(binding.btnPageFind);
                        }
                        else
                        {
                            RealViewContext.setSelectedView(binding.btnRealViewClose);
                        }
                    } else if (RealViewContext.getSelectedView() == binding.btnRealViewClose) {
                        RealViewContext.setSelectedView(binding.btnRealViewNextPage);
                    } else if (RealViewContext.getSelectedView() == binding.btnPageFind) {
                        RealViewContext.setSelectedView(binding.tvPageMinuteRight);
                    } else if (RealViewContext.getSelectedView() == binding.tvPageMinuteRight) {
                        RealViewContext.setSelectedView(binding.tvPageMinuteLeft);
                    } else if (RealViewContext.getSelectedView() == binding.tvPageMinuteLeft) {
                        RealViewContext.setSelectedView(binding.tvPageHourRight);
                    } else if (RealViewContext.getSelectedView() == binding.tvPageHourRight) {
                        RealViewContext.setSelectedView(binding.tvPageHourLeft);
                    } else if (RealViewContext.getSelectedView() == binding.tvPageHourLeft) {
                        RealViewContext.setSelectedView(binding.tvPageDayRight);
                    } else if (RealViewContext.getSelectedView() == binding.tvPageDayRight) {
                        RealViewContext.setSelectedView(binding.tvPageDayLeft);
                    } else if (RealViewContext.getSelectedView() == binding.tvPageDayLeft) {
                        RealViewContext.setSelectedView(binding.tvPageMonthRight);
                    } else if (RealViewContext.getSelectedView() == binding.tvPageMonthRight) {
                        RealViewContext.setSelectedView(binding.tvPageMonthLeft);
                    } else if (RealViewContext.getSelectedView() == binding.tvPageMonthLeft) {
                        RealViewContext.setSelectedView(binding.btnRealViewClose);
                    } else if (binding.btnRealViewNextPage.getVisibility() == View.VISIBLE) {
                        RealViewContext.setSelectedView(binding.btnRealViewNextPage);
                    } else {
                        RealViewContext.setSelectedView(binding.btnRealViewClose);
                    }

                    break;
                case ControlEventValues.RIGHT:

                    if (RealViewContext.getSelectedView() == binding.btnRealViewNextPage) {
                        RealViewContext.setSelectedView(binding.btnRealViewClose);
                    } else if (RealViewContext.getSelectedView() == binding.btnRealViewClose) {
                        if (binding.rlRealViewContainerItem2.getVisibility() == View.VISIBLE) {
                            RealViewContext.setSelectedView(binding.tvPageMonthLeft);
                        }
                        else if(binding.btnRealViewNextPage.getVisibility()== View.VISIBLE)
                        {
                            RealViewContext.setSelectedView(binding.btnRealViewNextPage);
                        }
                    } else if (RealViewContext.getSelectedView() == binding.tvPageMonthLeft) {
                        RealViewContext.setSelectedView(binding.tvPageMonthRight);
                    } else if (RealViewContext.getSelectedView() == binding.tvPageMonthRight) {
                        RealViewContext.setSelectedView(binding.tvPageDayLeft);
                    } else if (RealViewContext.getSelectedView() == binding.tvPageDayLeft) {
                        RealViewContext.setSelectedView(binding.tvPageDayRight);
                    } else if (RealViewContext.getSelectedView() == binding.tvPageDayRight) {
                        RealViewContext.setSelectedView(binding.tvPageHourLeft);
                    } else if (RealViewContext.getSelectedView() == binding.tvPageHourLeft) {
                        RealViewContext.setSelectedView(binding.tvPageHourRight);
                    } else if (RealViewContext.getSelectedView() == binding.tvPageHourRight) {
                        RealViewContext.setSelectedView(binding.tvPageMinuteLeft);
                    } else if (RealViewContext.getSelectedView() == binding.tvPageMinuteLeft) {
                        RealViewContext.setSelectedView(binding.tvPageMinuteRight);
                    } else if (RealViewContext.getSelectedView() == binding.tvPageMinuteRight) {
                        RealViewContext.setSelectedView(binding.btnPageFind);
                    } else if (RealViewContext.getSelectedView() == binding.btnPageFind) {
                        RealViewContext.setSelectedView(binding.btnRealViewNextPage);
                    } else if (binding.btnRealViewNextPage.getVisibility() == View.VISIBLE) {
                        RealViewContext.setSelectedView(binding.btnRealViewNextPage);
                    } else {
                        RealViewContext.setSelectedView(binding.btnRealViewClose);
                    }

                    break;

            }
        } else if (binding.rlLogChildButtonContainer.getVisibility() == View.VISIBLE) {

            switch (event.getClickValue()) {
                case ControlEventValues.ENTRY:
                    if (binding.btnLogChildErrSelection.getVisibility() == View.VISIBLE) {
                        binding.btnLogChildErrNormal.callOnClick();
                    } else if (binding.btnLogChildLuboSelection.getVisibility() == View.VISIBLE) {
                        binding.btnLogChildLuboNormal.callOnClick();
                    } else if (binding.btnLogChildOptionSelection.getVisibility() == View.VISIBLE) {
                        binding.btnLogChildOptionNormal.callOnClick();
                    } else {
                        binding.btnLogChildErrSelection.setVisibility(View.VISIBLE);
                    }
                    break;
                case ControlEventValues.LEFT:

                    if (binding.btnLogChildErrSelection.getVisibility() == View.VISIBLE) {
                        binding.btnLogChildErrSelection.setVisibility(View.GONE);
                        binding.rlLogChildButtonContainer.setVisibility(View.GONE);
                    } else if (binding.btnLogChildLuboSelection.getVisibility() == View.VISIBLE) {
                        binding.btnLogChildErrSelection.setVisibility(View.VISIBLE);
                        binding.btnLogChildLuboSelection.setVisibility(View.GONE);
                    } else if (binding.btnLogChildOptionSelection.getVisibility() == View.VISIBLE) {
                        binding.btnLogChildLuboSelection.setVisibility(View.VISIBLE);
                        binding.btnLogChildOptionSelection.setVisibility(View.GONE);
                    } else {
                        binding.btnLogChildErrSelection.setVisibility(View.VISIBLE);
                    }

                      /*
                     if (binding.btnLogChildErrSelection.getVisibility() == View.VISIBLE) {
                         binding.btnLogChildErrSelection.setVisibility(View.GONE);
                         binding.rlLogChildButtonContainer.setVisibility(View.GONE);
                     }  else if (binding.btnLogChildOptionSelection.getVisibility() == View.VISIBLE) {
                         binding.btnLogChildErrSelection.setVisibility(View.VISIBLE);
                         binding.btnLogChildOptionSelection.setVisibility(View.GONE);
                     } else {
                         binding.btnLogChildErrSelection.setVisibility(View.VISIBLE);
                     }

                       */
                    break;
                case ControlEventValues.RIGHT:

                    if (binding.btnLogChildErrSelection.getVisibility() == View.VISIBLE) {
                        binding.btnLogChildLuboSelection.setVisibility(View.VISIBLE);
                        binding.btnLogChildErrSelection.setVisibility(View.GONE);

                    } else if (binding.btnLogChildLuboSelection.getVisibility() == View.VISIBLE) {
                        binding.btnLogChildOptionSelection.setVisibility(View.VISIBLE);
                        binding.btnLogChildLuboSelection.setVisibility(View.GONE);
                    } else if (binding.btnLogChildOptionSelection.getVisibility() == View.VISIBLE) {
                        binding.btnLogChildOptionSelection.setVisibility(View.GONE);
                        binding.rlLogChildButtonContainer.setVisibility(View.GONE);
                    } else {
                        binding.btnLogChildErrSelection.setVisibility(View.VISIBLE);
                    }



                    /*
                     if (binding.btnLogChildErrSelection.getVisibility() == View.VISIBLE) {
                         binding.btnLogChildOptionSelection.setVisibility(View.VISIBLE);
                         binding.btnLogChildErrSelection.setVisibility(View.GONE);

                     }  else if (binding.btnLogChildOptionSelection.getVisibility() == View.VISIBLE) {
                         binding.btnLogChildOptionSelection.setVisibility(View.GONE);
                         binding.rlLogChildButtonContainer.setVisibility(View.GONE);
                     } else {
                         binding.btnLogChildErrSelection.setVisibility(View.VISIBLE);
                     }

                     */
                    break;
            }
        } else {
            Log.d("CONTROL", "MainActivify==>onMessageEvent==>" + event.getClickValue());
            if (controlType == ControlType.SUB && event.getClickValue() != ControlEventValues.SUB_TO_MAIN) {
                Log.d("DDDDDDDDDD", "ControlType" + controlType);
                EventBus.getDefault().post(new ControlsClickSubEvent(event.getClickValue()));
            } else {

                switch (event.getClickValue()) {

                    case ControlEventValues.ENTRY:
                        if (MainContext.getSelectedView() != null && MainContext.canClick) {
                            MainContext.entry();
                            MainContext.reset();
                        } else {
                            //确认键
                            switch (controlIndex) {
                                case MainButtonValues.DATA:
                                    openRealView();
                                    //EventBus.getDefault().post(new OnFragmentChangeEvent(R.layout.fragment_real_picture));
                                    break;
                                case MainButtonValues.COMMON_SETTING:

                                    status.currentPwdTargetSourceId = R.layout.fragment_common_setting;
                                    binding.rlKeyboardLockerConfirm.setVisibility(View.VISIBLE);
                                    //EventBus.getDefault().post(new OnFragmentChangeEvent(R.layout.fragment_common_setting));
                                    break;
                                case MainButtonValues.LOG:

                                    //EventBus.getDefault().post(new OnFragmentChangeEvent(R.layout.fragment_exception_log));
                                    binding.rlLogChildButtonContainer.setVisibility(View.VISIBLE);
                                    break;
                                case MainButtonValues.FACTORY_SETTING:

                                    status.currentPwdTargetSourceId = R.layout.fragment_factory_setting;
                                    binding.rlKeyboardLockerConfirm.setVisibility(View.VISIBLE);
                                    //EventBus.getDefault().post(new OnFragmentChangeEvent(R.layout.fragment_factory_setting));
                                    break;
                                case MainButtonValues.SWITCH:

                                    EventBus.getDefault().post(new OnFragmentChangeEvent(R.layout.fragment_switch_test));
                                    break;
                            }
                            controlType = ControlType.SUB;
                        }
                        break;
                    case ControlEventValues.LEFT:
                        if (MainContext.getSelectedView() != null && MainContext.canMove) {
                            MainContext.canMove = false;
                        } else {
                            MainContext.reset();
                            if (controlIndex > ControlIndex.LEFT_INDEX) {
                                Log.d("CONTROL", "左移一个");
                                controlIndex--;
                                selectView();
                            } else if (controlIndex == ControlIndex.EMPTY) {
                                Log.d("CONTROL", "左移循环到右");
                                controlIndex = ControlIndex.RIGHT_INDEX;
                                selectView();
                            } else {
                                //controlIndex = ControlIndex.RIGHT_INDEX;
                                Log.d("CONTROL", "进入SUB");
                                controlType = ControlType.SUB;
                                EventBus.getDefault().post(new ControlsClickSubEvent(event.getClickValue()));
                            }
                        }

                        //左键
                        break;
                    case ControlEventValues.RIGHT:
                        if (MainContext.getSelectedView() != null && MainContext.canMove) {
                            MainContext.canMove = false;
                        } else {
                            MainContext.reset();
                            if (controlIndex < ControlIndex.RIGHT_INDEX) {
                                Log.d("CONTROL", "右移一个");
                                controlIndex++;
                                selectView();
                            } else if (controlIndex == ControlIndex.EMPTY) {
                                Log.d("CONTROL", "右移循环到左");
                                controlIndex = ControlIndex.LEFT_INDEX;
                                selectView();
                            } else {
                                //controlIndex = ControlIndex.LEFT_INDEX;
                                Log.d("CONTROL", "进入SUB");
                                controlType = ControlType.SUB;
                                EventBus.getDefault().post(new ControlsClickSubEvent(event.getClickValue()));
                            }
                        }

                        //右键
                        break;
                    case ControlEventValues.SUB_TO_MAIN:
                        //切换键
                        if (binding.btnRealViewClose.getVisibility() == View.VISIBLE) {
                            MainContext.setSelectedView(binding.btnRealViewClose);
                        }
                        controlType = ControlType.MAIN;
                        controlIndex = ControlIndex.EMPTY;
                        break;
                }
            }
        }
    }


    private void selectView() {
        switch (controlIndex) {
            case MainButtonValues.DATA:

                SelectContext.setSelectedView(selectOne(binding.btnRealPicNormal, binding.btnRealPicSelection));
                break;
            case MainButtonValues.COMMON_SETTING:
                SelectContext.setSelectedView(selectOne(binding.btnCommonSettingNormal, binding.btnCommonSettingSelection));
                break;
            case MainButtonValues.LOG:
                SelectContext.setSelectedView(selectOne(binding.btnLogNormal, binding.btnLogSelection));
                break;
            case MainButtonValues.FACTORY_SETTING:
                SelectContext.setSelectedView(selectOne(binding.btnFactorySettingNormal, binding.btnFactorySettingSelection));
                break;
            case MainButtonValues.SWITCH:
                SelectContext.setSelectedView(selectOne(binding.btnSwitchTestNormal, binding.btnSwitchTestSelection));
                break;
        }
    }

    private TextView selectOne(TextView tv1, TextView tv2) {
        if (tv1.getVisibility() == View.VISIBLE) {
            return tv1;
        }
        return tv2;
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(KeyboardSelectionOpenEvent event) {
        if (canOptionKeyboard()) {
            KeyboardSelectContext.result = event.getCurrentData();
            KeyboardSelectContext.selectItem = event.getSelectItems();
            KeyboardSelectContext.reset();
            binding.rlSelector.setVisibility(View.VISIBLE);
            EventBus.getDefault().post(new KeyboardSelectionActionEvent(0, event.getCurrentData()));
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(KeyboardNumberOpenEvent event) {
        if (canOptionKeyboard()) {
            KeyboardContext.result = event.getCurrentValue();
            binding.rlKeyboard.setVisibility(View.VISIBLE);
            EventBus.getDefault().post(new KeyboardNumberActionEvent(0, event.getCurrentValue()));
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(KeyboardConfirmOpenEvent event) {
        if (canOptionKeyboard()) {
            KeyboardConfirmContext.tipMsg = event.getTipMsg();
            binding.rlKeyboardConfirm.setVisibility(View.VISIBLE);
            EventBus.getDefault().post(new KeyboardConfirmActionEvent(0));
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(KeyboardTimeOpenEvent event) {
        if (canOptionKeyboard()) {
            binding.rlKeyboardTime.setVisibility(View.VISIBLE);
            EventBus.getDefault().post(new KeyboardTimeActionEvent(0));
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(KeyboardLockerOpenEvent event) {
        if (canOptionKeyboard()) {
            binding.rlKeyboardLocker.setVisibility(View.VISIBLE);
            EventBus.getDefault().post(new KeyboardLockerActionEvent(0));
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(KeyboardStopOpenEvent event) {
        if (canOptionKeyboard()) {
            binding.rlKeyboardStop.setVisibility(View.VISIBLE);
            EventBus.getDefault().post(new KeyboardStopActionEvent(0));
            status.isStop = true;

            if (status.localToPlc != 2) {
                status.localPageIndex = PageIndex.H_STOP;
                BaseTask.toNewPage(status.localPageIndex);
            } else {
                if (status.plcPageIndex == PageIndex.H_STOP) {
                    status.localPageIndex = PageIndex.H_STOP;
                }
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(KeyboardStopCloseEvent event) {
        binding.rlKeyboardStop.setVisibility(View.GONE);
        status.isStop = false;
        if (status.localToPlc != 2) {
            status.localPageIndex = PageIndex.H_SWITCH;
            BaseTask.toNewPage(status.localPageIndex);
        } else {

        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(KeyboardNumberCloseEvent event) {
        binding.rlKeyboard.setVisibility(View.GONE);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(KeyboardSelectionCloseEvent event) {
        binding.rlSelector.setVisibility(View.GONE);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(KeyboardTimeCloseEvent event) {
        binding.rlKeyboardTime.setVisibility(View.GONE);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(RealViewOpenEvent event) {

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(RealViewCloseEvent event) {


    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        SerialPortApi.getInstance().close();

        avcPlayerHelper.close();
        AppUtils.getInstance().showButton(this);

        //unregisterAll();
        //unregisterReceiver(bluetoothReceiver);
    }

    private void closeVirtualKeys() {
        // 关闭底部虚拟按键
        View decorView = getWindow().getDecorView();
        int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY | View.SYSTEM_UI_FLAG_FULLSCREEN;
        decorView.setSystemUiVisibility(uiOptions);

        //隐藏通知
        Intent intent = new Intent();
        intent.setAction("lyzk.intent.systemui.hidestatusbar");
        intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
        sendBroadcast(intent);


        /********/////隐藏下方键

        Intent intent2 = new Intent();
        intent2.setAction("lyzk.intent.systemui.hidenavigation");
        intent2.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
        sendBroadcast(intent2);


    }

    // 将当前Activity窗口带到最前方
    private void moveToFront() {
        ActivityManager am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        if (am != null) {
            am.moveTaskToFront(getTaskId(), 0);
        }
    }

    private void resetKeyboard() {
        binding.rlHelpPrinciple.setVisibility(View.GONE);
        binding.rlHelpContact.setVisibility(View.GONE);
        binding.rlKeyboardLockerConfirm.setVisibility(View.GONE);
        binding.rlKeyboard.setVisibility(View.GONE);
        binding.rlSelector.setVisibility(View.GONE);
        binding.rlKeyboardTime.setVisibility(View.GONE);
        binding.rlKeyboardConfirm.setVisibility(View.GONE);
        binding.rlKeyboardLocker.setVisibility(View.GONE);
        binding.rlKeyboardStop.setVisibility(View.GONE);
    }

    private boolean canOptionKeyboard() {
        if (binding.rlKeyboardLockerConfirm.getVisibility() == View.VISIBLE) {
            return false;
        }
        if (binding.rlKeyboard.getVisibility() == View.VISIBLE) {
            return false;
        }
        if (binding.rlSelector.getVisibility() == View.VISIBLE) {
            return false;
        }
        if (binding.rlKeyboardTime.getVisibility() == View.VISIBLE) {
            return false;
        }
        if (binding.rlKeyboardConfirm.getVisibility() == View.VISIBLE) {
            return false;
        }
        if (binding.rlKeyboardLocker.getVisibility() == View.VISIBLE) {
            return false;
        }
        if (binding.rlKeyboardStop.getVisibility() == View.VISIBLE) {
            return false;
        }
        return true;
    }

    private boolean canToOther() {
        Log.d("BUTTON", "canToOther");
        if (status.isStop) {
            return false;
        }
        if (binding.rlKeyboardLockerConfirm.getVisibility() == View.VISIBLE) {
            return false;
        }
        if (binding.rlKeyboard.getVisibility() == View.VISIBLE) {
            return false;
        }
        if (binding.rlSelector.getVisibility() == View.VISIBLE) {
            return false;
        }
        if (binding.rlKeyboardTime.getVisibility() == View.VISIBLE) {
            return false;
        }
        if (binding.rlKeyboardConfirm.getVisibility() == View.VISIBLE) {
            return false;
        }
        if (binding.rlKeyboardLocker.getVisibility() == View.VISIBLE) {
            return false;
        }
        if (binding.rlKeyboardStop.getVisibility() == View.VISIBLE) {
            return false;
        }
        return true;
    }


    private void openRealView() {
        /***
         * 关闭下面的视频，切换上面的视频，该清清
         */
        resetPageCondition(new MyCalendar());
        binding.btnRealPicNormal.setTextColor(Color.WHITE);
        binding.btnRealPicSelection.setTextColor(Color.WHITE);
        binding.rlRealViewContainer.setVisibility(View.VISIBLE);
        binding.btnRealViewClose.setVisibility(View.VISIBLE);
        status.isOpenedRealView = true;

        EventBus.getDefault().post(new RealViewOpenEvent());
        avcPlayerHelper.pause(false);

        if (status.localToPlc != 2) {
            status.localPageIndex = PageIndex.H_REAL_VIEW;
            BaseTask.toNewPage(status.localPageIndex);
        } else {
            if (status.plcPageIndex == PageIndex.H_REAL_VIEW) {
                status.localPageIndex = PageIndex.H_REAL_VIEW;
            }
        }


        // resetOpenCamera();

    }

    private void closeRealView() {
        binding.rlRealViewContainer.setVisibility(View.GONE);
        status.isOpenedRealView = false;
        binding.btnRealViewClose.setVisibility(View.GONE);
        RealViewContext.setSelectedView(null);
        EventBus.getDefault().post(new RealViewCloseEvent());
        avcPlayerHelper.pause(true);

        if (status.localToPlc != 2) {
            status.localPageIndex = PageIndex.H_MAIN;
            BaseTask.toNewPage(status.localPageIndex);
        } else {

        }

        binding.rlKeyboard.setVisibility(View.GONE);
        binding.rlKeyboardConfirm.setVisibility(View.GONE);
        binding.rlKeyboardLockerConfirm.setVisibility(View.GONE);
        binding.rlKeyboardTime.setVisibility(View.GONE);
        binding.rlKeyboardLocker.setVisibility(View.GONE);


        // avcPlayerHelper.close();
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(TotalPopDataChangedEvent event) {
        //Log.d("AAAAAAA-SSSSSS",event.getElectricValues().length+"|"+ event.getVoltageValues().length);
        realViewTotalData.resetData(event);
    }
    DecimalFormat df = new DecimalFormat("#.#");
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(TemperatureDataEvent event) {
      //  if (status.isOpenedRealView) {
        Log.d("SHOOTLEE_TEMP","1");
            if (event.getIndex() == 0) {
                Log.d("SHOOTLEE_TEMP","10");
                binding.ivRealView.setImageBitmap(event.getImage());
                binding.ivRealViewHighMain.setText("腔内最高温度:"+df.format(status.temp_3584)+"°C");
                binding.ivRealViewLowMain.setText("腔内最低温度:"+df.format(status.temp_3587)+"°C");
                binding.ivRealViewAvgMain.setText("腔内平均温度:"+df.format(status.temp_avg_1)+"°C");
                Log.d("SHOOTLEE_TEMP","100");
            } else if (event.getIndex() == 1) {
                Log.d("SHOOTLEE_TEMP","11");
                binding.ivRealView.setImageBitmap(event.getImage());
                binding.ivRealViewHighMain.setText("腔内最高温度:"+df.format(status.temp_3585)+"°C");
                binding.ivRealViewLowMain.setText("腔内最低温度:"+df.format(status.temp_3588)+"°C");
                binding.ivRealViewAvgMain.setText("腔内平均温度:"+df.format(status.temp_avg_2)+"°C");
                Log.d("SHOOTLEE_TEMP","110");
            } else if (event.getIndex() == 2) {
                Log.d("SHOOTLEE_TEMP","12");
                binding.ivRealView.setImageBitmap(event.getImage());
                binding.ivRealViewHighMain.setText("腔内最高温度:"+df.format(status.temp_3586)+"°C");
                binding.ivRealViewLowMain.setText("腔内最低温度:"+df.format(status.temp_3589)+"°C");
                binding.ivRealViewAvgMain.setText("腔内平均温度:"+df.format(status.temp_avg_3)+"°C");
                Log.d("SHOOTLEE_TEMP","120");
            }
       // }
    }




    AvcPlayerHelper avcPlayerHelper = new AvcPlayerHelper();

    private void initIPCameraView1() {


        // "rtsp://"+ APPSPUtils.getInstance().getCameraIp()+":8554/profile0"
        avcPlayerHelper.initIPCameraView(binding.apRealView);

    }

    private void resetPlatform() {
        if (AppVariable.platform_version == 450 && AppVariable.need_reset_view) {
            int top = -25;
            int left = 0;

            ViewGroup.MarginLayoutParams layoutParams = (ViewGroup.MarginLayoutParams) binding.btnRealViewClose.getLayoutParams();
            int newtop = layoutParams.topMargin + top;
            int newleft = layoutParams.leftMargin + left;


            layoutParams.setMargins(newleft, newtop, 0, 0);
            binding.btnRealViewClose.setLayoutParams(layoutParams);


            ViewGroup.MarginLayoutParams layoutParams1 = (ViewGroup.MarginLayoutParams) binding.llButtonCaontainer.getLayoutParams();
            newtop = layoutParams1.topMargin + top;
            newleft = layoutParams1.leftMargin + left;
            layoutParams1.setMargins(newleft, newtop, 0, 0);
            binding.llButtonCaontainer.setLayoutParams(layoutParams1);


        }
    }

    private static final String TAG = "MainActivity";
    private UsbManager usbManager;
    private UsbDeviceReceiver usbDeviceReceiver;

    private void registerUsb() {
        usbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
        usbDeviceReceiver = new UsbDeviceReceiver(new UsbDeviceReceiver.UsbDeviceConnectionListener() {
            @Override
            public void onDeviceAttached(UsbDevice device) {
                Log.d(TAG, "Device attached: " + device.getDeviceName());

                ConnectStatus.setUsbConnected(true);

            }

            @Override
            public void onDeviceDetached(UsbDevice device) {
                Log.d(TAG, "Device detached: " + device.getDeviceName());
                ConnectStatus.setUsbConnected(false);
            }
        });

        IntentFilter filter = new IntentFilter();
        filter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);
        filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
        registerReceiver(usbDeviceReceiver, filter);
    }

    private BluetoothAdapter bluetoothAdapter;

    private void registerBluetooth() {
        bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

        // 注册广播接收器
        IntentFilter filter = new IntentFilter();
        filter.addAction(BluetoothDevice.ACTION_ACL_CONNECTED);
        filter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED);
        registerReceiver(bluetoothReceiver, filter);
    }

    private final BroadcastReceiver bluetoothReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (BluetoothDevice.ACTION_ACL_CONNECTED.equals(action)) {
                //BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                ConnectStatus.setBluetoothConnected(true);

            } else if (BluetoothDevice.ACTION_ACL_DISCONNECTED.equals(action)) {
                //BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                ConnectStatus.setBluetoothConnected(false);
            }
        }
    };

    private TelephonyManager telephonyManager;
    private PhoneStateListener phoneStateListener;
    private TelephonyCallback telephonyCallback;

    private void registerPhone() {
        telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            setupTelephonyCallback();
        } else {
            setupPhoneStateListener();
        }
    }

    private void setupTelephonyCallback() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            telephonyCallback = new TelephonyCallback() {
                // @Override
                public void onSignalStrengthsChanged(SignalStrength signalStrength) {
                    // super.onSignalStrengthsChanged(signalStrength);
                    updateSignalStatus(signalStrength);
                }

            };

            telephonyManager.registerTelephonyCallback(getMainExecutor(), telephonyCallback);
        }

    }

    private void setupPhoneStateListener() {
        phoneStateListener = new PhoneStateListener() {
            @Override
            public void onSignalStrengthsChanged(SignalStrength signalStrength) {
                super.onSignalStrengthsChanged(signalStrength);
                updateSignalStatus(signalStrength);
            }
        };
        telephonyManager.listen(phoneStateListener, PhoneStateListener.LISTEN_SIGNAL_STRENGTHS);
    }

    private void updateSignalStatus(SignalStrength signalStrength) {
        int gsmSignalStrength = signalStrength.getGsmSignalStrength();
        if (gsmSignalStrength != 99) {
            ConnectStatus.setMobileConnected(true);
        } else {
            ConnectStatus.setMobileConnected(false);
        }
    }

    EthernetBroadcastReceiver ethernetBroadcastReceiver;

    private void registerEther() {
        // 在Activity中注册BroadcastReceiver
        IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
        ethernetBroadcastReceiver = new EthernetBroadcastReceiver();
        registerReceiver(ethernetBroadcastReceiver, filter);

    }

    public void toMainPage(View view) {
        byte[] cmd = modbusUtil.writeToOne(1, CommonUtils.int2ByteArray(3529), new byte[]{0x00, 0});
        BaseTask.addNewPLCCommand(cmd);
    }


    public class EthernetBroadcastReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            Log.d("SHOOTLEE", "收到 EthernetBroadcastReceiver");
            ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
            if (networkInfo != null && networkInfo.getType() == ConnectivityManager.TYPE_ETHERNET) {
                if (networkInfo.isConnected()) {
                    // 以太网连接已建立
                    ConnectStatus.setEthernetConnected(true);
                } else {
                    // 以太网连接已断开
                    ConnectStatus.setEthernetConnected(false);
                }
            } else if (networkInfo != null && networkInfo.getType() == ConnectivityManager.TYPE_ETHERNET) {
                if (networkInfo.isConnected()) {
                    // 以太网连接已建立
                    ConnectStatus.setWifiConnected(true);
                } else {
                    // 以太网连接已断开
                    ConnectStatus.setWifiConnected(false);
                }
            }
        }
    }


    private void registerAll() {
        registerUsb();
        registerBluetooth();
        registerPhone();
        registerEther();
    }

    private void unregisterAll() {

        try {
            unregisterReceiver(usbDeviceReceiver);
            unregisterReceiver(bluetoothReceiver);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
                telephonyManager.unregisterTelephonyCallback(telephonyCallback);
            } else {
                telephonyManager.listen(phoneStateListener, PhoneStateListener.LISTEN_NONE);
            }
            unregisterReceiver(ethernetBroadcastReceiver);
        } catch (Exception e) {
        }

    }

    private void resetElement() {
        if (APPSPUtils.getInstance().get红外测温视频Switch().equals("开")) {
            //弹出页，有下一页，有那两个框框
            //底图变成bg_main_has

            binding.getRoot().setBackgroundResource(R.drawable.bg_main_has_right);
            binding.rlRealViewContainerItem1.setVisibility(View.VISIBLE);
            binding.rlRealViewContainerItem2.setVisibility(View.GONE);
            binding.btnRealViewNextPage.setVisibility(View.VISIBLE);

        } else {
            binding.rlRealViewContainerItem1.setVisibility(View.GONE);
            binding.rlRealViewContainerItem2.setVisibility(View.VISIBLE);
            binding.getRoot().setBackgroundResource(R.drawable.bg_main);
        }
    }

    private void resetOpenCamera() {
        binding.rlMainCameraContainer.removeAllViews();
        AvcPlayer avcPlayer = new AvcPlayer(this, null);

        // 设置布局参数（可选）
        FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT
        );
        avcPlayer.setLayoutParams(params);
        // 添加到容器
        binding.rlMainCameraContainer.addView(avcPlayer);
        avcPlayerHelper.initIPCameraView(avcPlayer);
    }



    private void testTotalData() {
        new Thread(new Runnable() {
            @Override
            public void run() {

                SystemClock.sleep(5000);
                while (true) {


                    int[] arrayV = new int[600];
                    int[] arrayEA = new int[600];
                    int[] arrayEB = new int[600];
                    int[] arrayE = new int[600];
                    int[] arrayEC = new int[600];

                    int indexV = 0;
                    int indexE = 0;
                    int indexEA = 100;
                    int indexEB = 150;
                    int indexEC = 200;

                    for (int i = 0; i < 600; i++) {

                        arrayV[i] = indexV;
                        arrayE[i] = indexE;
                        arrayEA[i] = indexEA;
                        arrayEB[i] = indexEB;
                        arrayEC[i] = indexEC;

                        indexV++;
                        if (indexV >= 400) {
                            indexV = 0;
                        }
                        indexE++;
                        if (indexE >= 400) {
                            indexE = 0;
                        }
                        indexEA++;
                        if (indexEA >= 400) {
                            indexEA = 0;
                        }
                        indexEB++;
                        if (indexEB >= 400) {
                            indexEB = 0;
                        }
                        indexEC++;
                        if (indexEC >= 400) {
                            indexEC = 0;
                        }

                    }

                    EventBus.getDefault().post(new TotalPopDataChangedEvent(arrayV, arrayE, arrayEA, arrayEB, arrayEC));
                    SystemClock.sleep(1000);
                }
            }
        }).start();
    }

    private void testAddData() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                int count = 3600 * 24 * 20;
                //int count = 10;
                long begin = System.currentTimeMillis() - 1000 * count;
                int addCount = 0;

                double[] avgEA = TotalData.generateRegularWave(10, 3, 3);
                double[] avgEB = TotalData.generateRegularWave(15, 4, 4);
                double[] avgEC = TotalData.generateRegularWave(20, 5, 5);
                double[] avgVA = TotalData.generateRegularWave(12, 3, 3);
                double[] avgVB = TotalData.generateRegularWave(18, 4, 4);
                double[] avgVC = TotalData.generateRegularWave(22, 5, 5);

                int indexEA = 0;
                int indexEB = 0;
                int indexEC = 0;
                int indexVA = 0;
                int indexVB = 0;
                int indexVC = 0;

                while (addCount < count) {
                    Log.d("ADDADDDATA", "共：" + count + " 当前：" + addCount);
                    int currentEA = 0;
                    int currentEB = 0;
                    int currentEC = 0;
                    int currentVA = 0;
                    int currentVB = 0;
                    int currentVC = 0;

                    if (avgEA.length > indexEA) {
                        currentEA = (int) Math.round(avgEA[indexEA] * 100);
                    } else {
                        indexEA = 0;
                        currentEA = (int) Math.round(avgEA[indexEA] * 100);
                    }
                    if (avgEB.length > indexEB) {
                        currentEB = (int) Math.round(avgEB[indexEB] * 100);
                    } else {
                        indexEB = 0;
                        currentEB = (int) Math.round(avgEB[indexEB] * 100);
                    }
                    if (avgEC.length > indexEC) {
                        currentEC = (int) Math.round(avgEC[indexEC] * 100);
                    } else {
                        indexEC = 0;
                        currentEC = (int) Math.round(avgEC[indexEC] * 100);
                    }
                    if (avgVA.length > indexVA) {
                        currentVA = (int) Math.round(avgVA[indexVA] * 100);
                    } else {
                        indexVA = 0;
                        currentVA = (int) Math.round(avgVA[indexVA] * 100);
                    }
                    if (avgVB.length > indexVB) {
                        currentVB = (int) Math.round(avgVB[indexVB] * 100);
                    } else {
                        indexVB = 0;
                        currentVB = (int) Math.round(avgVB[indexVB] * 100);
                    }
                    if (avgVC.length > indexVC) {
                        currentVC = (int) Math.round(avgVC[indexVC] * 100);
                    } else {
                        indexVC = 0;
                        currentVC = (int) Math.round(avgVC[indexVC] * 100);
                    }

                    NewTotalDataEntity newTotalDataEntity = NewTotalDataEntity.build(currentEA, currentEB, currentEC, currentVA, currentVB, currentVC, begin);
                    boolean isOk = newTotalDataEntity.save();
                    Log.d("ADDADDDATA", "添加结果：" + isOk);
                    SystemClock.sleep(2);
                    begin += 1000;
                    addCount++;

                    indexEA++;
                    indexEB++;
                    indexEC++;
                    indexVA++;
                    indexVB++;
                    indexVC++;
                }
            }
        }).start();
    }
    MyCalendar currentMyCalendar = new MyCalendar();
    private void resetPageCondition(MyCalendar date)
    {
        currentMyCalendar = date;
        binding.tvPageDayValue.setText( date.getDay()+ "日");
        binding.tvPageHourValue.setText(date.getHour()+ "时");
        binding.tvPageMinuteValue.setText(date.getMinute()+"分");
        binding.tvPageMonthValue.setText(date.getMonth()+"月");
    }


}